package com.qch.rabbitmq.demo;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.URI;

/**
 * @Author qch
 * @Date 2021/5/14
 */
@Configuration
public class RabbitConfig {
    //配置连接工厂
    @Bean
    public ConnectionFactory connectionFactory(){
        ConnectionFactory factory = new CachingConnectionFactory(URI.create("amqp://root:123456@192.168.142.135:5672/%2f"));
        return factory;
    }
    @Bean
    @Autowired //将工厂注入
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        return template;
    }
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory){
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        return rabbitAdmin;
    }
    @Bean
    public Queue queue(){
        final Queue queue = QueueBuilder.nonDurable("queue.ano").build();
        return queue;
    }
    @Bean
    public Exchange exchange(){
        FanoutExchange fanoutExchange = new FanoutExchange("ex.anno.fanout",false,false,null);
        return fanoutExchange;
    }
    //绑定
    @Bean
    @Autowired
    public Binding binding(Queue queue,Exchange exchange){
        //创建一个绑定，不指定绑定的参数
        Binding binding = BindingBuilder.bind(queue).to(exchange).with("key.anno").noargs();
        return binding;
    }
}
